package controllers

import (
	"day17zy/cache"
	"day17zy/models"
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"gorm.io/gorm"
	"strconv"
	"time"
)

type WWW struct {
	beego.Controller
}

type Msg struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (w *WWW) Add() {
	bos := w.GetString("bos")
	nie := w.GetString("nie")
	pin := w.GetString("pin")
	zuo := w.GetString("zuo")
	if bos == "" || nie == "" || pin == "" || zuo == "" {
		w.Data["json"] = Msg{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		w.ServeJSON()
		return
	}
	ww := models.Lyou{
		Bos: bos,
		Nie: nie,
		Pin: pin,
		Zuo: zuo,
	}
	err := models.DB.Create(&ww).Error
	var asd models.Lyou
	models.DB.Where("bos=?", bos).First(&asd)
	rediskey := "redis_id" + strconv.Itoa(int(asd.ID))
	asdJson, _ := json.Marshal(asd)
	cache.Rdb.Set(cache.Ctx, rediskey, asdJson, time.Hour*1)
	if err != nil {
		w.Data["json"] = Msg{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		w.ServeJSON()
		return
	} else {
		w.Data["json"] = Msg{
			Code: 200,
			Msg:  "添加成功",
			Data: ww,
		}
		w.ServeJSON()
	}
}
func (w *WWW) List() {
	var aa []models.Lyou
	ListKey := "Lists_id"
	ListDats, _ := cache.Rdb.Get(cache.Ctx, ListKey).Result()
	if ListDats == "" {
		err := models.DB.Find(&aa).Error
		redisJson, _ := json.Marshal(aa)
		cache.Rdb.Set(cache.Ctx, ListKey, redisJson, time.Hour*1)
		if err != nil {
			w.Data["json"] = Msg{
				Code: 0,
				Msg:  "查询失败",
				Data: nil,
			}
			w.ServeJSON()
			return
		} else {
			w.Data["json"] = Msg{
				Code: 200,
				Msg:  "查询成功",
				Data: aa,
			}
			w.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(ListDats), &aa)
	}
}
func (w *WWW) Updata() {
	bos := w.GetString("bos")
	nie := w.GetString("nie")
	pin := w.GetString("pin")
	zuo := w.GetString("zuo")
	id, _ := w.GetInt("id")
	if bos == "" || nie == "" || pin == "" || zuo == "" {
		w.Data["json"] = Msg{
			Code: 0,
			Msg:  "字段不能为空",
			Data: nil,
		}
		w.ServeJSON()
		return
	}
	ww := models.Lyou{
		Model: gorm.Model{ID: uint(id)},
		Bos:   bos,
		Nie:   nie,
		Pin:   pin,
		Zuo:   zuo,
	}
	err := models.DB.Updates(&ww).Error
	if err != nil {
		w.Data["json"] = Msg{
			Code: 0,
			Msg:  "修改失败",
			Data: nil,
		}
		w.ServeJSON()
		return
	} else {
		w.Data["json"] = Msg{
			Code: 200,
			Msg:  "修改成功",
			Data: ww,
		}
		w.ServeJSON()
	}
}
func (w *WWW) Del() {
	id, _ := w.GetInt("id")
	err := models.DB.Delete(&models.Lyou{}, id).Error
	rediskey := "redis_id" + strconv.Itoa(id)
	cache.Rdb.Del(cache.Ctx, rediskey)
	if err != nil {
		w.Data["json"] = Msg{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		w.ServeJSON()
		return
	} else {
		w.Data["json"] = Msg{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		w.ServeJSON()
	}
}
